package com.shioirikukuri.controller;

import com.shioirikukuri.dto.UserMemberDTO;
import com.shioirikukuri.entity.User;
import com.shioirikukuri.entity.UserMember;
import com.shioirikukuri.service.IUserMemberService;
import com.shioirikukuri.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/admin/user-members")
public class UserMemberController {
	@Autowired
	private IUserMemberService userMemberService;

	@Autowired
	private IUserService userService;

	/**
	 * 查询所有会员信息（DTO格式）
	 */
	@GetMapping
	public ResponseEntity<List<UserMemberDTO>> getAllUserMembers() {
		List<UserMember> members = userMemberService.getAllUserMembers();
		List<UserMemberDTO> dtos = members.stream()
				.map(this::convertToDTO)
				.filter(Objects::nonNull) // 过滤无效数据
				.collect(Collectors.toList());
		return ResponseEntity.ok(dtos);
	}

	/**
	 * 根据ID查询会员信息（DTO格式）
	 */
	@GetMapping("/{id}")
	public ResponseEntity<UserMemberDTO> getUserMemberById(@PathVariable Long id) {
		UserMember member = userMemberService.getUserMemberById(id);
		UserMemberDTO dto = convertToDTO(member);
		return dto != null ? ResponseEntity.ok(dto) : ResponseEntity.notFound().build();
	}

	/**
	 * 实体类转DTO（显式数据注入）
	 */
	private UserMemberDTO convertToDTO(UserMember member) {
		// 1. 获取用户信息（显式调用服务接口）
		Optional<User> userOpt = userService.getUserById(member.getUserId());
		if (!userOpt.isPresent()) {
			return null; // 用户不存在则跳过（或抛出异常）
		}
		User user = userOpt.get();

		// 2. 构建DTO（仅注入必要字段）
		return new UserMemberDTO(
				member.getId(),
				user.getPhoneNumber(),
				user.getFullName(),
				member.getCreatedAt(),
				member.getLevelId(),
				member.getTotalSpent(),
				member.getBalance()
		);
	}
}